package com.lu.test.aop;

import org.aopalliance.aop.Advice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.PointcutAdvisor;
import org.springframework.aop.SpringProxy;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.NameMatchMethodPointcut;

import java.lang.reflect.Method;

public class SpringProxyFactoryTest3 {
	public static void main(String[] args) {
		ProxyFactory proxyFactory = new ProxyFactory();
		// 添加代理逻辑+切入点 Advisor = advice+pointcut
		proxyFactory.addAdvisor(new MyAdvisor());
		// 设置代理对象
		proxyFactory.setTarget(new SpringProxyFactoryTestImpl());
		// 设置代理对象(一个空的代理对象)
		// proxyFactory.setTargetClass(SpringProxyFactoryTest.class);
		// 添加接口 并且接口类型不是 SpringProxy 直接走jdk代理
		proxyFactory.addInterface(SpringProxyFactoryTest.class);

		//
		SpringProxyFactoryTest proxy = (SpringProxyFactoryTest) proxyFactory.getProxy();
		proxy.test();
	}
}

class SpringProxyFactoryTestImpl implements SpringProxyFactoryTest {
	@Override
	public void test() {
		System.out.println("SpringProxyFactoryTest");
	}

}

interface SpringProxyFactoryTest extends SpringProxy {
	void test();
}

class MyAdvisor implements PointcutAdvisor {

	@Override
	public Pointcut getPointcut() {
		NameMatchMethodPointcut methodPointcut = new NameMatchMethodPointcut();
		methodPointcut.addMethodName("test");
		return methodPointcut;
	}

	@Override
	public Advice getAdvice() {
		MethodBeforeAdvice methodBeforeAdvice = new MethodBeforeAdvice() {
			@Override
			public void before(Method method, Object[] args, Object target) throws Throwable {
				System.out.println("执行方法前" + method.getName());
			}
		};

		return methodBeforeAdvice;
	}

	@Override
	public boolean isPerInstance() {
		return false;
	}
}